<template>
  <el-dialog
    ref="isPopWindows"
    v-dialogDrag
    title="提示"
    :visible.sync="isViewPart"
    width="70%"
    :append-to-body="true"
    :close-on-click-modal="false"
    center
    @close="close"
    @opened="open"
  >
    <dialogHeader
      slot="title"
      title="备件选择"
      :style-type="$store.state.app.dialogType"
    />
    <div class="formBoxContain" style="display: flex">
      <one-table-template
        ref="multipleTable"
        style="width: 70%"
        :dynamic-buttons="tableButtons"
        :dynamic-components="tableComponents"
        :dynamic-table-defult-height="350"
        :dynamic-api-config="dynamicApiConfigs"
        :dynamic-table-cols="tableCols"
        :dynamic-form-fields="formField"
        :dynamic-is-show-select="true"
        :dynamic-is-init-table="false"
        dynamic-table-ref="cusTable"
        :dynamic-is-show-more-btn="true"
        :dynamic-page-size="20"
        :callback-obj="callbackObj"
        :row-class-name="rowClassName"
        :stripe="false"
      />
      <div
        style="width: 30%;padding: 5px"
      >
        <div class="custom-title">
          <span class="blabel">已选择备件</span>
          <el-button @click="rightDelect" icon="el-icon-delete">删除</el-button>
          <el-button @click="subReData" icon="el-icon-check">确认</el-button>
        </div>
        <el-table
          :data="reData"
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="40"
            align="center"
          />
          <el-table-column
            type="index"
            width="40"
            label="序号"
            align="center"
          />
          <el-table-column
            prop="partNo"
            label="备件编码"
            align="center"
          />
          <el-table-column
            prop="partName"
            label="备件名称"
            align="center"
          />
        </el-table>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'
// import api from '@/api/vehicleManagement'

export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  props: {
    priceField: {
      type: String,
      default: 'purPrice'
    },
    closeDisabled: {
      type: Boolean,
      default: false
    },
    // 是否关闭弹窗
    isViewPart: {
      type: Boolean,
      default: false
    },
    rowData: {
      type: Object,
      default: () => ({})
    },
    chosenList: {
      type: Array,
      default: () => ([])
    },
    curSelectList: {
      type: Array,
      default: () => ([])
    },
    custom: {
      type: Object,
      default: () => ({})
    }
    // api: {
    //   type: Object,
    //   default: () => ({
    //     ServiceCode: 'queryPartList',
    //     APIUrl: '/mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/queryPartList.do'
    //   })
    // }
  },
  data() {
    null
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      selectiondata: [],
      selectiondataR: [],
      reData: [],
      // dynamicApiConfigs: vehiclePdiPriceInquirys.queryPartList,
      tableComponents:
        this.custom.tableComponents ||
         [
           {
             compKey: 'compKey1',
             labelName: '备件号：',
             codeField: 'partNo',
             component: () => import('@/components/org/commonInput'),
             isInput: true,
             isMust: true,
             span: 8
           },
           {
             compKey: 'compKey2',
             labelName: '备件名称：',
             codeField: 'partName',
             component: () => import('@/components/org/commonInput'),
             isInput: true,
             isMust: true,
             span: 8
           },
           // {
           //   compKey: 'compKey3',
           //   labelName: '所有者类型：',
           //   codeField: 'c',
           //   component: () => import('@/components/org/LookupValue'),
           //   oFields: 'statusId,statusText',
           //   options: [
           //     { statusId: '', statusText: '全部' },
           //     { statusId: '0', statusText: '总部' },
           //     { statusId: '1', statusText: '自定义' }
           //   ],
           //   type: 'dropdownList',
           //   isMul: false,
           //   isMust: true,
           //   span: 8
           // },
           // {
           //   compKey: 'compKey4',
           //   labelName: '备件属性：',
           //   codeField: 'd',
           //   component: () => import('@/components/org/LookupValue'),
           //   oFields: 'statusId,statusText',
           //   options: [
           //     { statusId: '', statusText: '全部' },
           //     { statusId: '0', statusText: '一般维修件' },
           //     { statusId: '1', statusText: '碰撞件' },
           //     { statusId: '2', statusText: '保养件' },
           //     { statusId: '3', statusText: '易损件' },
           //     { statusId: '4', statusText: '工具件' },
           //     { statusId: '5', statusText: '辅料' }
           //   ],
           //   type: 'dropdownList',
           //   isMul: false,
           //   isMust: false,
           //   span: 8
           // },
           {
             compKey: 'compKey5',
             labelName: '维修类别：',
             codeField: 'partRepairType',
             component: () => import('@/components/org/commonSelect'),
             oFields: 'partRepairType,partRepairTypeCn',
             customObj: {
               api: {
                 APIUrl: '/mp/e3sh/spareparts/finance/partDiscountSettingDlrService/queryRepairTypes.do'
               }
             },
             type: 'dropdownList',
             isMul: false,
             isMust: true,
             span: 8
           },
           // {
           //   compKey: 'compKey6',
           //   labelName: '适用车型：',
           //   codeField: 'carConfigCn',
           //   component: () => import('@/components/org/commonInput'),
           //   isInput: true,
           //   isMust: true,
           //   span: 8
           // },
           {
             compKey: 'compKey6',
             labelName: '适用车型：',
             codeField: 'carConfigCode',
             textField: 'carConfigCn',
             span: 8,
             component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
             dataToObject: {
               oFields: 'carConfigCode,carConfigCn',
               // 控制弹窗页面 搜索 网格 元素
               tableComponents: [
                 {
                   compKey: 'compKey1',
                   labelName: '车型编码：',
                   codeField: 'carConfigCode',
                   isMul: false,
                   component: () => import('@/components/org/commonInput'),
                   type: 'inputText',
                   isMust: true,
                   span: 8
                 },
                 {
                   compKey: 'compKey2',
                   labelName: '车型名称：',
                   codeField: 'carConfigCn',
                   isMul: false,
                   component: () => import('@/components/org/commonInput'),
                   type: 'inputText',
                   isMust: true,
                   span: 8
                 }
               ],
               tableCols: [
                 {
                   prop: 'carSeriesCode',
                   label: '车系编码'
                 },
                 {
                   prop: 'carSeriesCn',
                   label: '车系名称'
                 },
                 {
                   prop: 'carConfigCode',
                   label: '车型编码'
                 },
                 {
                   prop: 'carConfigCn',
                   label: '车型名称'
                 }
               ],
               formField: {
                 carConfigCode: '',
                 carConfigCn: ''
               },
               returnField: {
                 prop: 'carConfigCode',
                 label: '车型编码'
               },
               api: { APIUrl: 'mp/e3sh/spareparts/basic/partPriceQueryService/queryCarConfigCodes.do', ServiceCode: 'queryCarConfigCodes' }
             },
             type: 'inputText',
             isMul: false,
             isMust: true
           }
         ],
      formField: this.custom.formField || this.$utils.getFormField(this, {
        partNo: '',
        partName: '',
        partRepairType: '',
        carConfigCode: '',
        carConfigCn: ''
      }),
      // 回调方法
      callbackObj: {
        // 网格点击回调事件
        // onRowClick: (currentRow) => {
        //   this.onRightRowClick(currentRow)
        // },
        // 手动勾选网格时，拿到勾选网格的数据
        onCheckSelectChange: (selection, row) => {
          this.selectiondata = selection
        },
        // 选择项禁用  返回 false 为禁用
        onSelectable: (row, index) => {
          if (!this.closeDisabled) {
            // 开起禁用
            return Number(row[this.priceField]) && !this.chosenList.includes(row['partId'])
          } else {
            // 不禁用
            return true
          }
        }
      },
      tableButtons: [
        {
          compKey: 'button1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.open(),
          text: '查询',
          position: 'right'
        },
        {
          compKey: 'button1',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => {
            for (const attr in this.formField) {
              this.formField[attr] = ''
            }
          },
          text: '重置',
          position: 'right'
        },
        {
          compKey: 'button5',
          type: 'primary',
          size: 'small',
          icon: 'el-icon-plus',
          name: 'select',
          clickEvent: () => this.notarize(),
          text: '添加',
          position: 'left'
        }
        // {
        //   compKey: "button6",
        //   type: "",
        //   size: "small",
        //   icon: "",
        //   name: "delete",
        //   clickEvent: () => this.$refs.isPopWindowsTable.reset(),
        //   text: "删除",
        //   position: "right",
        // },
      ],
      // 动态生成网格列
      tableCols:
        this.custom.tableCols ||
         [
           {
             prop: 'partNo',
             label: '备件号',
             align: 'center',
             width: 100
           },
           {
             prop: 'partName',
             label: '备件名称',
             align: 'center',
             width: 135
           },
           {
             prop: 'unit',
             label: '计量单位',
             align: 'center'
           },
           {
             prop: 'minPurchasePage',
             label: '最小订货数',
             align: 'center'
           },
           {
             prop: 'purPrice',
             label: '单价',
             align: 'center',
             sortable: 'custom'
           },
           {
             prop: 'purQty',
             label: '订货数量',
             align: 'center',
             isComponent: true,
             hidden: true,
           },
           {
            //  prop: 'sumAccountQtyStatus',
             prop: 'oemUsableQtyCn',
             label: '总部库存状态',
             align: 'center'
           },
           // {
           //   prop: 'partAttr',
           //   label: '备件属性',
           //   align: 'center'
           // },
           {
             prop: 'partRepairTypeCn',
             label: '维修类别',
             align: 'center'
           },
           {
             prop: 'carConfigIdList',
             label: '适用车型',
             align: 'center',
             width: 150
           }
           // {
           //   prop: "repairOrderCode",
           //   label: "派工单号",
           //   align: "center",
           //   isComponent: true,
           // },
           // {
           //   prop: "vin",
           //   label: "VIN",
           //   align: "center",
           //   isComponent: true,

           // },
           // {
           //   prop: "carLicense",
           //   label: "车牌号",
           //   align: "center",
           //   isComponent: true,
           // },
           // {
           //   prop: "custName",
           //   label: "客户名称",
           //   align: "center",
           //   isComponent: true,
           // },
           // {
           //   prop: "custTel",
           //   label: "客户电话",
           //   align: "center",
           //   isComponent: true,
           // }
         ],
      dynamicApiConfigs: this.custom.api || {}
    }
  },
  mounted() {

  },
  methods: {
    // 提交
    subReData() {
      this.$emit('selectiondataPart', this.reData)
      this.$emit('update:is-view-part', false)
      // 清空数据
      this.selectiondata = []
      this.reData = []
    },
    // 右侧数据删除
    rightDelect() {
      const deleteDatas = this.selectiondataR.map(o => o.partId)
      this.reData = this.reData.reduce((newList, row) => {
        if (!deleteDatas.includes(row['partId'])) {
          newList.push(row)
        }
        return newList
      }, [])
      const lis = this.$utils.deepCopy(this.chosenList)
      this.$emit('update:chosenList', lis.reduce((newList, id) => {
        if (!deleteDatas.includes(id)) { newList.push(id) }
        return newList
      }, []))
    },
    // 右侧列表 勾选事件
    handleSelectionChange(selection) {
      this.selectiondataR = selection
    },
    rowClassName({ row }) {
      if (this.chosenList.includes(row['partId'])) {
        return 'warning-row'
      }
      return ''
    },
    /**
     * @description 关闭弹窗
     * @time 2021、01、22
     */
    close() {
      this.reData = []
      for (const attr in this.formField) {
        this.formField[attr] = ''
      }
      this.$emit('update:is-view-part', false)
    },
    setRightTableDatas() {
      this.reData = this.curSelectList
    },
    open() {
      console.log('触发')
      this.setRightTableDatas()
      const that = this.$refs['multipleTable']
      if (this.rowData.isHq) {
        // 总部 api
        that.apiConfig = { APIUrl: '/mp/e3sh/spareparts/sparePartsOrderMakingService/queryPartChoose.do' }
      } else if (this.custom.api) {
        console.log('api',this.custom.api)
        that.apiConfig = this.custom.api
      } else {
        // 网点 api
        that.apiConfig = { APIUrl: '/mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/queryPartList.do' }
      }
      // 页， dataType, 每页数量, 请求成功回调, 自定义参数
      that.queryTable(1, '', 20, '', (res) => {
        // 请求成功回调
      }, {
        formField: {
          ...this.formField,
          supplierId: this.rowData.supplierId || '',
          supplierCode: this.rowData.supplierCode || ''
        }
      })
    },
    addIndex(rows) {
      rows.forEach((row, index) => {
        if (!row.hasOwnProperty('index')) {
          row['index'] = index
        }
      })
      return rows
    },
    // 清除勾选
    clearAllSelect() {
      this.$refs['multipleTable'].$refs['cusTable'].clearSelection()
    },
    // 确认
    notarize() {
      if (!this.selectiondata.length) return this.$message('请先选择要添加的数据！')
      this.reData.push(...this.selectiondata)
      // this.$parent.chosenList.push(
      //   ...this.selectiondata.map(o => o.partId)
      // )
      const lis = this.$utils.deepCopy(this.chosenList)
      lis.push(...this.selectiondata.map(o => o.partId))
      this.$emit('update:chosenList', lis)
      // 清除勾选
      this.clearAllSelect()
    }
  }
}
</script>
<style lang="css" scoped>
  >>>.el-table .warning-row {
    background: #f3d6c9;
  }

  .custom-title{
    margin-bottom: 0;
    padding: 8px 8px 12px;
    background: linear-gradient(to right, #94bde3, #b3eff6);
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: auto;
    font-size: 14px;
    border-radius: 4px 4px 0 0;
  }
  .blabel {
    font-weight: bold;
  }
</style>
